package cn.ivicar.iov.service.impl;

import cn.ivicar.iov.dao.FlowPackageHistoryDao;
import cn.ivicar.iov.dao.IdentifyDao;
import cn.ivicar.iov.dao.SimPresentFlowInfoDao;
import cn.ivicar.iov.dao.VehicleDao;
import cn.ivicar.iov.entity.FlowPackageHistory;
import cn.ivicar.iov.entity.SimPresentFlowInfo;
import cn.ivicar.iov.entity.Vehicle;
import cn.ivicar.iov.entity.VehicleSim;
import cn.ivicar.iov.dao.SimPresentFlowInfoDao;
import cn.ivicar.iov.service.SimPresentFlowInfoService;
import cn.ivicar.iov.util.DateUtil;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.google.gson.JsonObject;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.*;

/**
 * @program: iov
 * @description: ${description}
 * @author: Mr.huang
 * @create: 2018-08-21 15:59
 **/
@Service
@Component
public class SimPresentFlowInfoServiceImpl implements SimPresentFlowInfoService {

    private static final String USER_ID = "bjxyq9706";
    private static final String USER_PWD = "bjxy007";

    @Autowired
    private SimPresentFlowInfoDao simPresentFlowInfoDao;
    @Autowired
    private VehicleDao vehicleDao;
    @Autowired
    private IdentifyDao identifyDao;
    @Autowired
    private FlowPackageHistoryDao flowPackageHistoryDao;

    List list = new ArrayList();
    List list1 = new ArrayList();

    //每天0点将续费期更新为正常状态
    @Transactional
    @Scheduled(cron = "0 0 0 * * ?")
    @Override
    public boolean modifyNormalStatus() throws IOException {
        int effectedNum = simPresentFlowInfoDao.updateNormalStatus();
        if (effectedNum > 0) {
            return true;
        } else {
            System.out.println("暂不能将续费期改为正常");
            return true;
        }
    }

    //每天0点将体验期更新为正常状态
    @Transactional
    @Scheduled(cron = "0 0 0 * * ?")
    @Override
    public boolean modifyProbationStatus() throws IOException {
        int effectedNum = simPresentFlowInfoDao.updateProbationStatus();
        if (effectedNum > 0) {
            return true;
        } else {
            System.out.println("暂不能将体验期改为正常");
            return true;
        }
    }


    //每月1号，更新当前套餐信息表
    @Transactional
    @Scheduled(cron = "0 0 0 1 * ?")
    @Override
    public boolean ChangePackage() {
        List<FlowPackageHistory> flowPackageHistoryList = flowPackageHistoryDao.queryFlowPackageByTime();
        for (int i = 0; i < flowPackageHistoryList.size(); i++) {
            SimPresentFlowInfo simPresentFlowInfo = new SimPresentFlowInfo();
            simPresentFlowInfo.setIccid(flowPackageHistoryList.get(i).getIccid());
            simPresentFlowInfo.setFlow_package_id(flowPackageHistoryList.get(i).getFlow_package_id());
            simPresentFlowInfo.setStart_time(flowPackageHistoryList.get(i).getStart_time());
            simPresentFlowInfo.setEnd_time(flowPackageHistoryList.get(i).getEnd_time());
            simPresentFlowInfoDao.updateSimPresentFlowInfo(simPresentFlowInfo);
        }
        return true;
    }

    //更改服务截止时间
    @Override
    public boolean modifyDeadline(String vehicle_serial) {
        boolean IsTrue = false;
        Date date = flowPackageHistoryDao.queryMaxEndTime(identifyDao.queryByVehicleId(vehicleDao.queryVehicleId(vehicle_serial)));
        int effectNum = simPresentFlowInfoDao.upadateDeadLine(identifyDao.queryByVehicleId(vehicleDao.queryVehicleId(vehicle_serial)), date);
        if (effectNum > 0) {
            IsTrue = true;
        }
        return IsTrue;
    }

    //一号更新正常状态为续费期并推送
    @Transactional
    @Scheduled(cron = "0 0 0 1 * ?")
    @Override
    public boolean modifyRenewStatus1() throws IOException {
            int effectedNum = simPresentFlowInfoDao.updateRenewStatus();
            list = simPresentFlowInfoDao.queryRenewCustomer();
            list1 = simPresentFlowInfoDao.queryProbationCustomer();
            list.addAll(list1);
            messagePush(list);
            if (effectedNum > 0) {
                return true;
            } else {
                System.out.println("无需要进行改动的内容");
                return true;
            }
    }

    //15号推送
    @Transactional
    @Scheduled(cron = "0 0 0 15 * ?")
    @Override
    public boolean modifyRenewStatus2() throws IOException {
        int effectedNum = simPresentFlowInfoDao.updateRenewStatus();
        list = simPresentFlowInfoDao.queryRenewCustomer();
        list1 = simPresentFlowInfoDao.queryProbationCustomer();
        list.addAll(list1);
        messagePush(list);
        if (effectedNum > 0) {
            return true;
        } else {
            System.out.println("无需要进行改动的内容");
            return true;
        }
    }

    //25号推送
    @Transactional
    @Scheduled(cron = "0 0 0 25 * ?")
    @Override
    public boolean modifyRenewStatus3() throws IOException {
        int effectedNum = simPresentFlowInfoDao.updateRenewStatus();
        list = simPresentFlowInfoDao.queryRenewCustomer();
        list1 = simPresentFlowInfoDao.queryProbationCustomer();
        list.addAll(list1);
        messagePush(list);
        if (effectedNum > 0) {
            return true;
        } else {
            System.out.println("无需要进行改动的内容");
            return true;
        }
    }

    //26号把所有过期未缴费的卡注销
    @Transactional
    @Scheduled(cron = "0 0 0 26 * ?")
    @Override
    public boolean modifyCancelStatus() throws IOException {
        int effectedNum = simPresentFlowInfoDao.updateCancelStatus();
        if (effectedNum > 0) {
            return true;
        } else {
            System.out.println("无需要进行改动的内容");
            return true;
        }
    }

    @Override
    public boolean messagePush(List list) {
        boolean isPush = false;
        String alert = "This is a pushMsg.";
        final String appkey = "b61859c47d52e438b715f81a";
        final String mastersecret = "6835bde8aa5ce87e530bccdc";
        JPushClient jPushClient = new JPushClient(mastersecret, appkey);
        Calendar calendar = Calendar.getInstance();
        Date date= new Date();
        calendar.set(Calendar.DATE, 1);
        calendar.roll(Calendar.DATE, -1);

        int currentDays = calendar.get(Calendar.DATE);
        int lastdays;
        if (currentDays == 31) {
            calendar.setTime(date);
            lastdays = 31 - calendar.get(Calendar.DATE);
        } else if (currentDays == 28) {
            lastdays = 28 - calendar.get(Calendar.DATE);
        } else if (currentDays == 29) {
            lastdays = 29 - calendar.get(Calendar.DATE);
        } else {
            lastdays = 30 - calendar.get(Calendar.DATE);
        }
        PushPayload pushPayload = PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.registrationId(list))
                .setNotification(Notification.newBuilder().addPlatformNotification(IosNotification.newBuilder()
                        .setAlert(alert)
                        .setBadge(1)
                        .setSound("happy.caf")
                        .addExtra("from", "Jpush")
                        .build())
                        .build())
                .setMessage(Message.content("您的余额已不足，剩余天数为"+lastdays))
                .setOptions(Options.newBuilder()
                        .setApnsProduction(true)
                        .build())
                .build();
        try {
            PushResult pushResult = jPushClient.sendPush(pushPayload);
            System.out.println("success");
            isPush = true;
            return isPush;
        } catch (APIConnectionException e) {
            e.printStackTrace();
            System.err.println("errMsg" + e.getMessage());
        } catch (APIRequestException e) {
            e.printStackTrace();
            System.err.println("errMsg" + e.getMessage());
        }
        return isPush;
    }

    //从车机端收到iccid和激活时间后，往数据库表中插入一条数据
    @Override
    public boolean addVehicleSimInfo(String iccid, Date date) {
        DateUtil dateUtil = new DateUtil();
        Date endTime = dateUtil.getProbationEndTime(date);
        SimPresentFlowInfo simPresentFlowInfo = new SimPresentFlowInfo();
        simPresentFlowInfo.setIccid(iccid);
        simPresentFlowInfo.setStart_time(date);
        simPresentFlowInfo.setEnd_time(endTime);
        simPresentFlowInfo.setStatus(2);
        simPresentFlowInfo.setDeadline(endTime);
        int effNum = simPresentFlowInfoDao.insertVehicleSimInfo(simPresentFlowInfo);
        if(effNum>0){
            return true;
        }
        else {
            return false;
        }
    }

//
//    @Override
//    public JSONObject getMonthFlowUsed() {
//        String columnName = "iccid";
//        String transId = String.valueOf(System.currentTimeMillis());
//        Map<String, String> params = generateCommonParams(columnName, iccid, transId);
//        List<String> signParams = new ArrayList<>();
//        signParams.add(columnName);
//        signParams.add(iccid);
//        signParams.add(transId);
//        signParams.add(USER_ID);
//        signParams.add(USER_PWD);
//        String sign = createSign(signParams);
//        params.put("sign", sign);
//
//
//        String result = sendPostRequest(URL_SIM_FLOW_USED_MONTHLY_REALTIME, params);
//        if(StringUtils.isBlank(result)){
//            return null;
//        }
//
//        JSONObject json = JSONObject.fromObject(result);
//        return json;
//    }
//    private static String createSign(List<String> params){
//        String charset="UTF-8";
//        StringBuffer sbuf = new StringBuffer();
//        for(String temp : params){
//            sbuf.append(temp);
//        }
//
//        return Md5Utils.MD5Encode(sbuf.toString(), charset, false);
//    }
//
//    private static Map<String, String> generateCommonParams(String columnName, String columnValue, String transId){
//        Map<String, String> params = new HashMap<>();
//        params.put("userId", USER_ID);
//        params.put("transId", transId);
//        params.put("column_name", columnName);
//        params.put("column_value", columnValue);
//
//        return params;
//    }
//
//    private static String sendPostRequest(String url, Map<String, String> params){
//        System.out.println("url=" + url);
//        System.out.println("params=" + params);
//        String content = "";
//        HttpClient client = new HttpClient();
//        PostMethod method = new PostMethod(url);
//
//        Iterator<Map.Entry<String, String>> ps = params.entrySet().iterator();
//        while (ps.hasNext()) {
//            Map.Entry<String, String> p = ps.next();
//            method.addParameter(p.getKey(), p.getValue().toString());
//        }
//
//        try {
//            int statusCode = client.executeMethod(method);
//            if (statusCode != HttpStatus.SC_OK) {
//                System.out.println("post请求失败:  statusCode:" + statusCode + " statusLine:" + method.getStatusLine());
//            } else {
//                content = method.getResponseBodyAsString();
//            }
//        }catch(Exception e){
//            e.printStackTrace();
//        }
//
//        return content;
//    }
}
